import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getProductsByCategory } from '@/api/ProductApi';
import { getAllCategoryList } from '@/api/CategoryApi';
import { ElMessage } from 'element-plus'

/**
 * 分类数据存储
 */
export const useCategoryStore = defineStore('category', () => {
  // 分类数据
  const categories = ref([])
  const activeIndex = ref(0)

  // 商品数据
  const productsMap = ref({}) // 按分类ID存储商品数据
  const paginationMap = ref({}) // 按分类ID存储分页数据
  const loading = ref(false)

  // 获取当前分类ID
  const currentCategoryId = computed(() => {
    return categories.value[activeIndex.value]?.categoryId || ''
  })

  // 获取当前分类的商品
  const currentProducts = computed(() => {
    if (!currentCategoryId.value) return []
    return productsMap.value[currentCategoryId.value] || []
  })

  // 获取当前分类的分页信息
  const currentPagination = computed(() => {
    if (!currentCategoryId.value) {
 return {
      current: 1,
      size: 2,
      total: 0,
      pages: 0
    }
}
    return paginationMap.value[currentCategoryId.value] || {
      current: 1,
      size: 2,
      total: 0,
      pages: 0
    }
  })

  // 加载分类数据
  const loadCategories = async () => {
    try {
      loading.value = true
      const response = await getAllCategoryList()

      if (response.code === 1) {
        categories.value = response.data
      } else {
        ElMessage.error(response.msg || '获取分类失败')
      }
    } catch (error) {
      console.error('获取分类列表失败:', error)
      ElMessage.error('加载分类列表失败')
    } finally {
      loading.value = false
    }
  }

  // 加载商品数据
  const loadProducts = async (categoryId, page = 1, size = 2) => {
    if (!categoryId || loading.value) return

    try {
      loading.value = true
      const response = await getProductsByCategory(categoryId, page, size)

      if (response.code === 1) {
        const data = response.data

        // 初始化分类数据
        if (!productsMap.value[categoryId]) {
          productsMap.value[categoryId] = []
        }

        // 如果是第一页，重置数据
        if (page === 1) {
          productsMap.value[categoryId] = data.records
        } else {
          productsMap.value[categoryId] = [...productsMap.value[categoryId], ...data.records]
        }

        // 更新分页信息
        paginationMap.value[categoryId] = {
          current: data.current,
          size: data.size,
          total: data.total,
          pages: data.pages
        }
      } else {
        ElMessage.error(response.msg || '获取商品失败')
      }
    } catch (error) {
      console.error('获取商品列表失败:', error)
      ElMessage.error('加载商品列表失败')
    } finally {
      loading.value = false
    }
  }

  // 切换分类
  const changeCategory = async (index) => {
    if (activeIndex.value === index) return

    activeIndex.value = index
    const categoryId = currentCategoryId.value

    // 如果该分类还没有加载过商品数据，则加载
    if (!productsMap.value[categoryId]) {
      await loadProducts(categoryId)
    }
  }

  // 加载更多商品
  const loadMoreProducts = async () => {
    const categoryId = currentCategoryId.value
    const pagination = currentPagination.value

    if (pagination.current < pagination.pages) {
      await loadProducts(categoryId, pagination.current + 1, pagination.size)
    }
  }

  // 初始化加载
  const initialize = async () => {
    if (categories.value.length === 0) {
      await loadCategories()
    }

    if (categories.value.length > 0 && !productsMap.value[currentCategoryId.value]) {
      await loadProducts(currentCategoryId.value)
    }
  }

  return {
    categories,
    activeIndex,
    currentCategoryId,
    currentProducts,
    currentPagination,
    loading,

    loadCategories,
    loadProducts,
    changeCategory,
    loadMoreProducts,
    initialize
  }
});